import { ElImageViewer } from 'element-plus'
import { createVNode, mergeProps, onBeforeUnmount, render, shallowRef } from 'vue'

export const useImageViewer = () => {
    const vnode = shallowRef()
    let container

    const ImageViewer = (props = {}) => {
        const { onClose: _onClose = () => {}, ...args } = props

        const defaultProps = {
            zoomRate: 1.3,
            urlList: []
        }

        const _props = mergeProps(defaultProps, args, {
            onClose: () => {
                destory()
                _onClose()
            }
        })

        vnode.value = createVNode(ElImageViewer, _props)
        container = document.createElement('div')
        render(vnode.value, container)
        document.body.appendChild(container.firstElementChild)
    }

    const destory = () => {
        container && render(null, container)
        vnode.value = null
        container = null
    }

    onBeforeUnmount(() => {
        destory()
    })

    return {
        vnode,
        ImageViewer
    }
}